package com.ccb.testcenter.configuration;

import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;

import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.ccb.testcenter.configuration.io.Resources;

public class XMLTestEntryResolver implements EntityResolver{
	 private static final String test_scheml="xtest.xsd";
	@Override
	public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
		
		 try {
		      if (systemId != null) {
		        String lowerCaseSystemId = systemId.toLowerCase(Locale.ENGLISH);
		        if (lowerCaseSystemId.contains(test_scheml)) {
		          return getInputSource(test_scheml, publicId, systemId);
		        } 
		      }
		      return null;
		    } catch (Exception e) {
		      throw new SAXException(e.toString());
		    }
	}
	
	  private InputSource getInputSource(String path, String publicId, String systemId) {
		    InputSource source = null;
		    if (path != null) {
		      try {
		        InputStream in = Resources.getResourceAsStream(path);
		        source = new InputSource(in);
		        source.setPublicId(publicId);
		        source.setSystemId(systemId);        
		      } catch (IOException e) {
		        // ignore, null is ok
		      }
		    }
		    return source;
		  }

}
